import React, { PropTypes } from 'react'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import { Spin } from 'antd'
import StationList from '../components/station/list'
import StationSearch from '../components/station/search'
import StationModal from '../components/station/modal'

/**
 * 站点信息列表
 */
function Station ({ location, dispatch, app,station }) {
  const {login}=app;
  const {loading,list, pagination, currentItem, modalVisible, modalType } = station;
  const { field, keyword } = location.query;

  const stationModalProps = {
    item: modalType === 'create' ? {} : currentItem,
    type: modalType,
    visible: modalVisible,
    onOk (data) {
      dispatch({
        type: `station/${modalType}`,
        payload: data
      })
    },
    onCancel () {
      dispatch({
        type: 'station/hideModal'
      })
    }
  };

  const stationListProps = {
    dataSource: list,
    loading,
    pagination: pagination,
    onPageChange (page) {

      const { query, pathname } = location;
      dispatch(routerRedux.push({
        pathname: pathname,
        query: {
          ...query,
          page: page.current,
          pageSize: page.pageSize
        }
      }))
    },
    onDeleteItem (id) {
      dispatch({
        type: 'station/delete',
        payload: id
      })
    },
    onEditItem (item) {
      dispatch({
        type: 'station/showModal',
        payload: {
          modalType: 'update',
          currentItem: item
        }
      })
    }
  };

  const stationSearchProps = {
    field,
    keyword,
    onSearch (fieldsValue) {
      fieldsValue.keyword.length ? dispatch(routerRedux.push({
        pathname: '/station',
        query: {
          field: fieldsValue.field,
          keyword: fieldsValue.keyword
        }
      })) : dispatch(routerRedux.push({
        pathname: '/station'
      }))
    },
    onAdd () {
      dispatch({
        type: 'station/showModal',
        payload: {
          modalType: 'create'
        }
      })
    }
  };

  const StationModalGen = () =>
    <StationModal {...stationModalProps} />;
  return (
    <div className='content-inner'>
      <Spin tip='loading...' spinning={loading} size='large'>
      <StationSearch {...stationSearchProps} />
      <StationList {...stationListProps} />
      <StationModalGen />
      </Spin>
    </div>
  )
}

Station.propTypes = {
  station: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func
};

function mapStateToProps ({ app,station }) {
  return { app,station }
}

export default connect(mapStateToProps)(Station)
